package com.example.interceptor;



import com.alibaba.fastjson.JSONObject;
import com.example.pojo.Result;
import com.example.utils.JwtUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

//拦截器属于SpringMVC
@Component
public class LoginCheckinterceptor implements HandlerInterceptor {

    @Override//目标资源方法运行前运行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取请求url
        String req = request.getRequestURL().toString();

        //2.判断req有没有login
        if(req.contains("login")){
            //有的话就是登录操作，放行
            return true;
        }

        //3.获取请求头中的令牌
        String Jwt = request.getHeader("token");

        //4.令牌不存在，放回json错误信息
        if(!StringUtils.hasLength(Jwt)){
            Result result = Result.error("NOT_LOGIN");
            //没有@ResponseBody注解,需要手动配置返回json格式 --- 阿里巴巴 fastjson
            String error = JSONObject.toJSONString(result);
            //将字符串响应给浏览器
            response.getWriter().write(error);
            return false;
        }

        //5.解析token
        try{
            JwtUtils.parseJWT(Jwt);
        }catch (Exception e){
            e.printStackTrace();
            Result result = Result.error("未登录");
            //没有@ResponseBody注解,需要手动配置返回json格式 --- 阿里巴巴 fastjson
            String error = JSONObject.toJSONString(result);
            //将字符串响应给浏览器
            response.getWriter().write(error);
            return false;
        }
        //返回true代表放行
        return true;
    }

    @Override//目标资源运行后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override//视图渲染完毕后
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
